import { _decorator, Node, AnimationClip, Component, ERigidBody2DType, math, PolygonCollider2D, RigidBody2D, Sprite, UITransform, Vec2, Vec3, PhysicsSystem2D, ERaycast2DType } from 'cc';
import { DIRECTION_ENUM, EAT_STATUS_ENUM, GAME_MODE_ENUM, PARAME_NAME_ENUM, PHY_GROUP, PLAYER_ENUM, SOCKET_TYPE } from '../../Enums';
import { createUINode, generateEllipsePoints, getEnemyManager, getFrameAllAsset, getFrameAsset } from '../utils';
import { PlayManager } from '../Player/PlayManager';
import DataManager from '../Runtime/DataManager';
import { AttackManager } from './AttackManager';
import { GameElement } from '../UI/GameElement';
import EventManager from '../Runtime/EventManager';
import { userStore } from '../service/user';
import { sendSocket } from '../service/socket';
const { ccclass } = _decorator;
@ccclass('GamePlayer')
export class GamePlayer extends Component {
    playManager: PlayManager
    userNode: Node
    attackPlayer: AttackManager
    status: string = ""
    modify: boolean = true //防止前方有障碍物时提前走几像素
    pre_status: string  //上一个动画状态
    next_status: string = ""  //上一个按键没松开,但是按了别的按键,最后按下的按钮
    lastPosition: Vec3
    timeout
    dizzy: Boolean = false
    disabled: Boolean = false
    disable_status: Array<string> = [] //用于多人模式的镜头跟随
    callback
    speed = 10
    death_timeout
    play_node
    defaultX = -150 / 2
    defaultY = 50
    node_name: string
    get state() {
        return this.playManager.state
    }
    set state(value: PARAME_NAME_ENUM) {
        if (this.play_node && this.play_node.isValid) {
            clearTimeout(this.callback)
            this.playManager.state = value
            this.playManager.sprite.trim = true
            this.playManager.sprite.sizeMode = Sprite.SizeMode.TRIMMED
            const transform = this.userNode.getComponent(UITransform)
            // 吞食动画需要调整坐标
            if (value == PARAME_NAME_ENUM.LEFTPROCESS) {
                this.userNode.setPosition(this.defaultX + 134, this.defaultY)
                transform.setAnchorPoint(1, 0.5)
                this.callback = setTimeout(() => {
                    this.state = PARAME_NAME_ENUM.IDLE
                }, 550)
                return
            }
            if (value == PARAME_NAME_ENUM.RIGHTPROCESS) {
                this.userNode.setPosition(this.defaultX + 20, this.defaultY)
                this.callback = setTimeout(() => {
                    this.state = PARAME_NAME_ENUM.IDLE
                }, 550)
                return
            }
            if (value == PARAME_NAME_ENUM.BOTTOMPROCESS) {
                this.userNode.setPosition(this.defaultX - 18, this.defaultY + 85)
                transform.setAnchorPoint(0, 1)
                return
            }
            if (value == PARAME_NAME_ENUM.TOPPROCESS) {
                this.userNode.setPosition(this.defaultX - 15, this.defaultY - 90)
                transform.setAnchorPoint(0, 0)
                return
            }
            // 吞食动画需要调整坐标-end
            transform.setAnchorPoint(0, 0.5)
            if ((value == PARAME_NAME_ENUM.LEFT || value == PARAME_NAME_ENUM.RIGHT) || this.playManager.direction == DIRECTION_ENUM.LEFT || this.playManager.direction == DIRECTION_ENUM.RIGHT) {
                this.userNode.setPosition(this.defaultX + 10, this.defaultY)
                return
            }
            if (this.playManager.direction == DIRECTION_ENUM.TOP) {
                this.userNode.setPosition(this.defaultX - 15, this.defaultY)
                return
            }
            this.userNode.setPosition(this.defaultX - 18, this.defaultY)
        }
    }
    set direction(value: DIRECTION_ENUM) {
        if (this.play_node && this.play_node.isValid) {
            this.playManager.direction = value
        }
    }
    set eatFood(value: EAT_STATUS_ENUM) {
        if (this.play_node && this.play_node.isValid) {
            this.playManager.eatFood = value
        }
    }
    async init(type: PLAYER_ENUM) {
        const node = createUINode("role")
        node.setParent(this.node)
        this.disable_status = []
        this.play_node = node
        const rigidBody2D = this.node.addComponent(RigidBody2D)
        rigidBody2D.gravityScale = 0
        rigidBody2D.fixedRotation = true
        rigidBody2D.group = type == 'blueLead' ? PHY_GROUP.SELF_PLANE : PHY_GROUP.NPC_PLANE
        rigidBody2D.type = ERigidBody2DType.Dynamic
        rigidBody2D.enabledContactListener = true
        const polygonCollider2D = this.node.addComponent(PolygonCollider2D)
        polygonCollider2D.points = [...generateEllipsePoints()]
        // polygonCollider2D.sensor=true
        let list = this.setRoleloadDir(type)
        const shadow = createUINode("shadow")
        shadow.setParent(node)
        const shadowSprite = shadow.addComponent(Sprite)
        shadowSprite.spriteFrame = getFrameAsset(DataManager.Instance.mapAssets, 'shadow.png').spriteFrame // DataManager.Instance.mapAssets.find(item => item.name == 'shadow')
        shadowSprite.color = new math.Color("#ffffff90")
        const shadowTransform = shadow.addComponent(UITransform)
        shadowTransform.setContentSize(DataManager.Instance.width, DataManager.Instance.position)
        const userNode = createUINode('userNode')
        userNode.setParent(node)
        userNode.setPosition(this.defaultX - 18, this.defaultY)
        const playManager = userNode.addComponent(PlayManager)
        playManager.init(list)
        userNode.setScale(2.5, 2.5)
        // 隐形子弹
        const attackPlayer = node.addComponent(AttackManager)
        this.attackPlayer = attackPlayer
        this.playManager = playManager
        this.userNode = userNode
        playManager.type = type
        if (DataManager.Instance.gameMode == GAME_MODE_ENUM.ONLINE) {
            EventManager.Instance.on("msg", this.websocketMessage, this)
        } else {
            EventManager.Instance.on('setStatus', this.setStatus, this);
            EventManager.Instance.on('setEatStatus', this.setEatStatus, this);
            EventManager.Instance.on('setStatusEnd', this.setStatusEnd, this);
        }
    }
    // 获取角色的状态信息
    getSendData() {
        let { ownerId, memberId } = DataManager.Instance.room
        if (this.node && this.node.isValid) {
            let { direction, eatFood, type, state } = this.playManager
            return {
                name: this.node.name,// 名称
                control_id: type == PLAYER_ENUM.BLUE ? ownerId : memberId, // 控制角色的用户id
                x: Math.round(this.node.getPosition().x / this.speed) * this.speed,// 位置
                y: Math.round(this.node.getPosition().y / this.speed) * this.speed,
                status: this.status,// 状态
                direction,//方向
                dizzy: this.dizzy,
                state,
                eatName: DataManager.Instance.eatName,
                eatFood,// 吃没吃东西
            }
        } else {
            return {
                name: null,// 名称
                control_id: null, // 控制角色的用户id
                x: null,// 位置
                y: null,
                status: null,// 状态
                direction: null,//方向
                dizzy: true,
                state: null,
                eatName: null,
                eatFood: null,// 吃没吃东西
            }
        }

    }
    // 强制设置角色的状态
    setSendData(data) {
        // console.log(data, "data")
        if (!data) return
        this.node.setPosition(data.x, data.y) // 位置
        if (this.status != data.status) {
            this.status = data.status
        }
        if (this.state != data.state) {
            this.state = data.state
        }
        this.direction = data.direction//方向
        if (data.dizzy) {
            this.characterDeath()
        }
        if (data.eatFood != this.playManager.eatFood) {
            this.eatFood = data.eatFood// 吃没吃东西
            this.state = data.state
        }
        DataManager.Instance.eatName = data.eatName
    }
    async websocketMessage(data) {
        if(data.type == SOCKET_TYPE.JOYSTICK||data.type == SOCKET_TYPE.JOYSTICKEAT||data.type == SOCKET_TYPE.JOYSTICKEND){
            let id = userStore()?.info?.id
            if (!id) return
            if (data.roomId != DataManager.Instance.room.id) return
            if (this.node.name != data.content.name) return
           
            if (data.type == SOCKET_TYPE.JOYSTICK) {
                this.setStatus(data.content.status)
            }
            if (data.type == SOCKET_TYPE.JOYSTICKEAT) {
                this.setEatStatus()
            }
            if (data.type == SOCKET_TYPE.JOYSTICKEND) {
                this.setStatusEnd(data.content.status)
            }
        }
       
    }
    onDestroy() {
        clearTimeout(this.death_timeout)
        if (DataManager.Instance.gameMode == GAME_MODE_ENUM.ONLINE) {
            EventManager.Instance.off('msg', this.websocketMessage);
        } else {
            EventManager.Instance.off('setStatus', this.setStatus);
            EventManager.Instance.off('setEatStatus', this.setEatStatus);
            EventManager.Instance.off('setStatusEnd', this.setStatusEnd);
        }

    }
    setEatStatus() {
        if (!this.playManager) return
        let { direction, eatFood } = this.playManager
        // 进行吃东西动画的时候禁止点击
        if (!this.playManager.fsm.paramsName.includes('idle')) return
        if (eatFood == EAT_STATUS_ENUM.EMPTY) {
            this.attackPlayer.launchAttack(EAT_STATUS_ENUM.EMPTY, direction)
            if (direction == DIRECTION_ENUM.TOP) {
                this.state = PARAME_NAME_ENUM.TOPPROCESS
            } else if (direction == DIRECTION_ENUM.LEFT) {
                this.state = PARAME_NAME_ENUM.LEFTPROCESS
            } else if (direction == DIRECTION_ENUM.BOTTOM) {
                this.state = PARAME_NAME_ENUM.BOTTOMPROCESS
            } else if (direction == DIRECTION_ENUM.RIGHT) {
                this.state = PARAME_NAME_ENUM.RIGHTPROCESS
            }
            DataManager.Instance.audioMgr.playOneShot(DataManager.Instance.audio.find(item => item.name == '1229'))
            return
        } else {
            // 如果面前有障碍物,就不能吐
            let list = this.playManager.obstacle.filter(item => item.active == true && !item.name.includes("enemy"))
            if (list.length > 0) return
            this.eatFood = EAT_STATUS_ENUM.EMPTY
            if (direction == DIRECTION_ENUM.TOP) {
                this.state = PARAME_NAME_ENUM.TOPPROCESS
            } else if (direction == DIRECTION_ENUM.LEFT) {
                this.state = PARAME_NAME_ENUM.LEFTPROCESS
            } else if (direction == DIRECTION_ENUM.BOTTOM) {
                this.state = PARAME_NAME_ENUM.BOTTOMPROCESS
            } else if (direction == DIRECTION_ENUM.RIGHT) {
                this.state = PARAME_NAME_ENUM.RIGHTPROCESS
            }
            // 延时，配合动画
            setTimeout(() => {
                DataManager.Instance.audioMgr.playOneShot(DataManager.Instance.audio.find(item => item.name == '1233'))
                this.attackPlayer.launchAttack(eatFood, direction)
            }, 300)

        }
    }
    // 摇杆按钮结束触摸
    setStatusEnd(value) {
        this.next_status = ""
        this.status = ""
        if (!this.playManager.forcedWalking) {
            this.walkingLogic(value)
        }
    }
    // 设置图片数组
    setRoleloadDir(role: string) {
        let typeList = []
        for (let key in PARAME_NAME_ENUM) {
            if (PARAME_NAME_ENUM.hasOwnProperty(key)) { // 确保key是对象自身的属性
                typeList.push(PARAME_NAME_ENUM[key])
            }
        }
        let arr = role == 'blueLead' ? DataManager.Instance.blueLeadAssets : DataManager.Instance.greenLeadAssets
        let list = []
        for (let i = 0; i < typeList.length; i++) {
            let item = typeList[i]
            let title = `${item}/`
            let spriteList = arr.jsonAsset.filter(item => item.filename.includes(`${title}`))
            list.push({
                type: item,
                name: role + '_' + item,
                spriteList: getFrameAllAsset(arr, spriteList),
                wrapMode: item.includes("process") || item.includes("dizzy") ? AnimationClip.WrapMode.Default : AnimationClip.WrapMode.Loop,
            })
        }
        return list
    }
    // 修改status  如果有了新的状态,就在当前状态执行完之后,忽略掉当前的状态,执行新的状态
    setStatus(value) {
        if (DataManager.Instance.enemyList.length == 0) return // 怪物没有了,代表胜利了,就不让移动了
        if (this.playManager.state == PARAME_NAME_ENUM.DIZZY || this.playManager.state == PARAME_NAME_ENUM.WIN) return
        if (this.dizzy && value != '') return //死亡状态可以把状态置空
        if (this.playManager.fsm.paramsName.includes('process')) return //吃东西的过程禁止切换
        if (this.playManager.disabled) return //如果正在移动中,禁止切换状态
        if (this.status == value) return //如果新状态和就状态一样,就禁止切换,防止键盘长按一直切换状态
        // 如果上个按键没松开,就不会改变状态,如果松开了,就把状态置为空,如果松开了但是按着别的按键,就执行最后按的那个按钮的状态
        if (this.status != '' && value != '') {
            this.next_status = value
            if (!this.playManager.forcedWalking) {
                this.walkingLogic(this.status)
            }
            return
        }

        let modify = true
        switch (value) {
            case "top":
                this.direction = DIRECTION_ENUM.TOP
                this.state = PARAME_NAME_ENUM.TOP
                break;
            case "left":
                this.direction = DIRECTION_ENUM.LEFT
                this.state = PARAME_NAME_ENUM.LEFT
                break;
            case "bottom":
                this.direction = DIRECTION_ENUM.BOTTOM
                this.state = PARAME_NAME_ENUM.BOTTOM
                break;
            case "right":
                this.direction = DIRECTION_ENUM.RIGHT
                this.state = PARAME_NAME_ENUM.RIGHT
                break;
            case "":
                this.status = ""
                break;
        }
        if (value != "") {
            // 射线检测，检测方向的下一格有没有角色或者怪物
            modify = this.getPhysicsAABB()
        }
        this.modify = modify
        this.status = value
    }
    // 获取上下左右得障碍物信息
    getPhysicsAABB() {
        let modify = true
        let start = new Vec2(this.node.getWorldPosition().x, this.node.getWorldPosition().y)
        let endX = this.node.getWorldPosition().x
        let endY = this.node.getWorldPosition().y
        if (this.playManager.direction == DIRECTION_ENUM.TOP) {
            endY = endY + 120
        } else if (this.playManager.direction == DIRECTION_ENUM.BOTTOM) {
            endY = endY - 120
        } else if (this.playManager.direction == DIRECTION_ENUM.LEFT) {
            endX = endX - 120
        } else if (this.playManager.direction == DIRECTION_ENUM.RIGHT) {
            endX = endX + 120
        }
        let end = new Vec2(endX, endY)
        const results = PhysicsSystem2D.instance.raycast(start, end, ERaycast2DType.All);
        let filterName = ['sensor', 'children_lurker', 'slide']
        let list = results.filter((item => !filterName.find(item1 => item.collider.node.name.includes(item1))))
        if (list.length > 0) {
            let collider = this.coordinateComparison(list)
            this.playManager.obstacle[0] = collider
            if (collider.name.includes("enemy")) {
                let manager = collider.getComponent(getEnemyManager(collider))
                // 如果晕倒了，就不让往前走
                modify = !manager.dizzy
            }
            if (collider.name.includes("role")) {
                modify = false
            }
        }
        return modify
    }
    // 射线检测,判断面前是否有障碍物
    physicsRaycast(force: Boolean = false) {
        if (!force) {
            if (this.playManager.state == PARAME_NAME_ENUM.IDLE) return
        }
        if (this.playManager.state == PARAME_NAME_ENUM.RIGHTPROCESS) return
        if (this.playManager.state == PARAME_NAME_ENUM.LEFTPROCESS) return
        if (this.playManager.state == PARAME_NAME_ENUM.BOTTOMPROCESS) return
        if (this.playManager.state == PARAME_NAME_ENUM.TOPPROCESS) return
        if (this.playManager.state == PARAME_NAME_ENUM.DIZZY) return
        let start = new Vec2(this.node.getWorldPosition().x, this.node.getWorldPosition().y)
        let endX = this.node.getWorldPosition().x
        let endY = this.node.getWorldPosition().y
        if (this.playManager.direction == DIRECTION_ENUM.TOP) {
            endY = endY + 120
        } else if (this.playManager.direction == DIRECTION_ENUM.BOTTOM) {
            endY = endY - 120
        } else if (this.playManager.direction == DIRECTION_ENUM.LEFT) {
            endX = endX - 150
        } else if (this.playManager.direction == DIRECTION_ENUM.RIGHT) {
            endX = endX + 150
        }
        let end = new Vec2(endX, endY)
        let { x, y } = this.node.getPosition()
        y = Math.round(y / this.speed) * this.speed
        x = Math.round(x / this.speed) * this.speed
        const results = PhysicsSystem2D.instance.raycast(start, end, ERaycast2DType.All);
        let filterName = ['sensor', 'children_lurker', 'slide']
        let list = results.filter((item => !filterName.find(item1 => item.collider.node.name.includes(item1))))
        if (list.length > 0) {
            let collider = this.coordinateComparison(list)
            let { x: collider_x, y: collider_y } = collider.getPosition()
            collider_y = Math.round(collider_y / this.speed) * this.speed
            collider_x = Math.round(collider_x / this.speed) * this.speed
            if (collider.name.includes("enemy")) {
                let manager = collider.getComponent(getEnemyManager(collider))
                // 如果晕倒了，就不让往前走
                if (manager.dizzy || manager.avoid) {
                    let walking = true
                    if (this.playManager.direction == DIRECTION_ENUM.TOP) {
                        if (Math.abs(y - collider_y) < 95) {
                            this.playManager.end_w = y + 30
                        } else {
                            walking = false
                        }
                    } else if (this.playManager.direction == DIRECTION_ENUM.BOTTOM) {
                        if (Math.abs(y - collider_y) == 90) {
                            this.playManager.end_s = y
                        } else {
                            walking = false
                        }
                    } else if (this.playManager.direction == DIRECTION_ENUM.LEFT) {
                        if (Math.abs(x - collider_x) != 150) {
                            walking = false
                        } else {
                            this.playManager.end_a = x
                        }
                    } else if (this.playManager.direction == DIRECTION_ENUM.RIGHT) {
                        if (Math.abs(x - collider_x) != 150) {
                            walking = false
                        } else {
                            this.playManager.end_d = x
                        }
                    } else {
                        this.setEndValue(collider)
                    }
                    if (walking) {
                        this.walkingLogic(this.playManager.direction)
                    }
                } else {
                    this.setEndValue(collider)
                }
            } else if (collider.name.includes("role")) {
                this.playManager.obstacle[0] = collider
                let manager = collider.getComponent(GamePlayer).playManager.fsm
                if (manager.paramsName == PARAME_NAME_ENUM.IDLE || manager.paramsName == PARAME_NAME_ENUM.DIZZY) {
                    let walking = true
                    if (this.playManager.direction == DIRECTION_ENUM.TOP) {
                        if (Math.abs(y - collider_y) < 95) {
                            this.playManager.end_w = y + 30
                        } else {
                            walking = false
                        }
                    } else if (this.playManager.direction == DIRECTION_ENUM.BOTTOM) {
                        if (Math.abs(y - collider_y) == 90) {
                            this.playManager.end_s = y
                        } else {
                            walking = false
                        }
                    } else if (this.playManager.direction == DIRECTION_ENUM.LEFT) {
                        if (Math.abs(x - collider_x) != 150) {
                            walking = false
                        } else {
                            this.playManager.end_a = x
                        }
                    } else if (this.playManager.direction == DIRECTION_ENUM.RIGHT) {
                        if (Math.abs(x - collider_x) != 150) {
                            walking = false
                        } else {
                            this.playManager.end_d = x
                        }
                    } else {
                        this.setEndValue(collider)
                    }
                    if (walking) {
                        this.walkingLogic(this.playManager.direction)
                    }
                } else {
                    // this.setEndValue(collider)
                }
            } else {
                this.playManager.obstacle[0] = collider
                this.setEndValue(collider)
            }
            return true
        } else {
            if (this.playManager.direction == DIRECTION_ENUM.TOP) {
                this.playManager.end_w = 0
            } else if (this.playManager.direction == DIRECTION_ENUM.BOTTOM) {
                this.playManager.end_s = 0
            } else if (this.playManager.direction == DIRECTION_ENUM.LEFT) {
                this.playManager.end_a = 0
            } else if (this.playManager.direction == DIRECTION_ENUM.RIGHT) {
                this.playManager.end_d = 0
            }
            this.playManager.obstacle = []
            return false
        }
    }
    setEndValue(collider) {
        let { height, width, position } = DataManager.Instance
        let { x, y } = collider.getPosition()
        y = Math.round(y / this.speed) * this.speed
        x = Math.round(x / this.speed) * this.speed
        if (this.playManager.direction == DIRECTION_ENUM.TOP) {
            this.playManager.end_w = y - ((height - position) / 2) - position
        } else if (this.playManager.direction == DIRECTION_ENUM.BOTTOM) {
            this.playManager.end_s = y + (height - position)
        } else if (this.playManager.direction == DIRECTION_ENUM.LEFT) {
            this.playManager.end_a = x + width
        } else if (this.playManager.direction == DIRECTION_ENUM.RIGHT) {
            this.playManager.end_d = x - width
        }
    }
    // 比较两个坐标哪个离目标坐标更近
    coordinateComparison(list) {
        let target = new Vec2(this.node.getWorldPosition().x, this.node.getWorldPosition().y)
        let nodeList = []
        list.forEach(item => {
            let point = item.point
            nodeList.push({
                node: item.collider.node,
                number: Math.sqrt(Math.pow(point.x - target.x, 2) + Math.pow(point.y - target.y, 2))
            })
        })
        let min = nodeList.sort((a, b) => {
            return a.number - b.number
        })
        return min[0].node
    }

    // 角色死亡
    characterDeath() {
        // return
        if (this.dizzy) return
        this.dizzy = true
        this.playManager.targetX = 0
        this.playManager.targetY = 0
        this.playManager.state = PARAME_NAME_ENUM.DIZZY
        if (this.playManager.direction == DIRECTION_ENUM.LEFT || this.playManager.direction == DIRECTION_ENUM.RIGHT) {
            this.userNode.setPosition(this.defaultX - 12, this.defaultY)
        }
        let rb = this.node.getComponent(RigidBody2D)
        rb!.linearVelocity = new Vec2(0, 0);;
        let polygonCollider2D = this.node.getComponent(PolygonCollider2D)
        polygonCollider2D.sensor = true
        setTimeout(() => {
            polygonCollider2D.apply()
        }, 5)
        let index = DataManager.Instance.player.findIndex(item => item.node.uuid == this.node.uuid)
        if (index != -1) {
            DataManager.Instance.player.splice(index, 1)
            if (DataManager.Instance.player.length == 1) {
                if(DataManager.Instance.gameMode==GAME_MODE_ENUM.ONLINE){
                    if(!DataManager.Instance.otherLine){
                        this.createElementFail()
                        return
                    }
                }
                setTimeout(() => {
                    // this.node.destroy()
                    this.node.active = false
                }, 3000)
            } else {
                this.createElementFail()
            }
        }
    }
    // 创建离线弹框
    createElementFail(){
        DataManager.Instance.audioMgr.playOneShot(DataManager.Instance.audio.find(item => item.name == '1297'))
        this.death_timeout = setTimeout(() => {
            // this.node.destroy()
            this.node.active = false
            if (DataManager.Instance.gameMode == GAME_MODE_ENUM.ONLINE) {
                sendSocket(SOCKET_TYPE.FAIL, {})
            } else {
                this.node.parent.parent.getComponent(GameElement).createFail()
            }
        }, 3000)
    }
    update() {
        if (this.dizzy) return
        let rb = this.node.getComponent(RigidBody2D)
        let speed = this.speed
        let lv = rb!.linearVelocity;
        let { x, y } = this.node.getPosition()
        y = Math.round(y / speed) * speed
        x = Math.round(x / speed) * speed
        if (this.status == "left" && this.disable_status.indexOf("left") < 0) {
            if (this.modify) {
                lv.x = -speed;
                lv = new Vec2(lv.x, 0);
            }
        } else if (this.status == "right" && this.disable_status.indexOf("right") < 0) {
            if (this.modify) {
                lv.x = speed;
                lv = new Vec2(lv.x, 0);
            }
        } else if (this.status == "top" && this.disable_status.indexOf("top") < 0) {
            if (this.modify) {
                lv.y = +speed;
                lv = new Vec2(0, lv.y);
            }
        } else if (this.status == "bottom" && this.disable_status.indexOf("bottom") < 0) {
            if (this.modify) {
                lv.y = -speed;
                lv = new Vec2(0, lv.y);
            }
        } else {
            lv = new Vec2(0, 0);
        }
        let { targetX, targetY, direction } = this.playManager
        if (direction == DIRECTION_ENUM.LEFT || direction == DIRECTION_ENUM.RIGHT) {
            if (targetX != 0) {
                if (x > parseInt(targetX + '')) {
                    lv.x = -speed;
                    lv = new Vec2(lv.x, 0);
                    this.playManager.disabled = true
                } else if (x < parseInt(targetX + '')) {
                    lv.x = +speed;
                    lv = new Vec2(lv.x, 0);
                    this.playManager.disabled = true
                } else {
                    lv = new Vec2(0, 0);
                    this.node.setPosition(targetX, y)
                    this.playManager.targetX = 0
                    this.playManager.targetY = 0
                    this.playManager.disabled = false
                    if (this.next_status != '') {
                        this.status = ""
                        this.setStatus(this.next_status)
                        this.next_status = ""
                        if (!this.playManager.forcedWalking) {
                            this.walkingLogic(this.next_status)
                        }
                    } else {
                        if (this.status == "") {
                            this.state = PARAME_NAME_ENUM.IDLE
                        }
                    }
                }
            }
        }
        if (direction == DIRECTION_ENUM.TOP || direction == DIRECTION_ENUM.BOTTOM) {
            if (targetY != 0) {
                if (y < parseInt(targetY + '')) {
                    lv.y = +speed;
                    lv = new Vec2(0, lv.y);
                    this.playManager.disabled = true
                } else if (y > parseInt(targetY + '')) {
                    lv.y = -speed;
                    lv = new Vec2(0, lv.y);
                    this.playManager.disabled = true
                } else {
                    this.node.setPosition(x, targetY)
                    this.playManager.targetY = 0
                    this.playManager.targetX = 0
                    lv = new Vec2(0, 0);
                    this.playManager.disabled = false
                    if (this.next_status != '') {
                        this.status = ""
                        this.setStatus(this.next_status)
                        this.next_status = ""
                        if (!this.playManager.forcedWalking) {
                            this.walkingLogic(this.next_status)
                        }
                    } else {
                        if (this.status == "") {
                            this.state = PARAME_NAME_ENUM.IDLE
                        }
                    }
                }
            }
        }
        rb!.linearVelocity = lv;
        // 判断前方有没有障碍物
        this.physicsRaycast()
    }

    // 获取停止后的坐标
    walkingLogic(keyCode) {
        let { width, position, mapWidth, mapHeight, height } = DataManager.Instance
        let nodePostion = this.node.getPosition()
        let { targetX, targetY, end_w, end_a, end_s, end_d } = this.playManager
        let { x, y } = nodePostion
        let tempX = targetX == 0 ? parseInt(x + '') : targetX
        let tempY = targetY == 0 ? parseInt(y + '') : targetY
        let endW = end_w == 0 ? -(position + ((height - position) / 2)) : end_w
        let endS = end_s == 0 ? -(mapHeight - height) : end_s
        let powerX, powerY
        switch (keyCode) {
            case "top":
                powerY = Math.floor((y + 20) / position)
                tempY = position * powerY + height - position
                if (tempY > endW) {
                    tempY = endW
                }
                break;
            case "bottom":
                powerY = Math.floor((y + 30) / position)
                tempY = position * powerY - ((height - position) / 2)
                if (tempY <= endS) {
                    tempY = endS
                }
                break;
            case "left":
                powerX = Math.floor(parseInt(x + '') / width)
                // 小于最小宽度的话，就不赋值
                let endA = end_a == 0 ? width * powerX : end_a
                if (width <= endA) {
                    tempX = endA
                }
                break;
            case "right":
                // 向上取整
                powerX = Math.ceil(parseInt(x + '') / width)
                let endD = end_d == 0 ? width * powerX : end_d
                // 超过最大宽度的话，就不赋值
                if (mapWidth - (2 * width) >= endD) {
                    tempX = endD
                }
                break;
        }
        this.playManager.targetX = Math.round(tempX / this.speed) * this.speed
        this.playManager.targetY = Math.round(tempY / this.speed) * this.speed
    }

}